<template>
  <div class="container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-button
          class="el-icon-back"
          type="primary"
          size="mini"
          @click="back()"
          >返回</el-button
        >
      </div>
      <div style="height: 100%">
        <el-row>
          <el-form
            label-width="98px"
            label-position="right"
            :model="edit"
            ref="edit"
            style="
              display: flex;
              justify-content: space-between;
              flex-wrap: wrap;
            "
          >
            <el-form-item label="产品名称">
              <el-input
                clearable
                size="mini"
                v-model="edit.productName"
                placeholder="请输入产品名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="单位">
              <el-select
                filterable
                size="mini"
                clearable
                v-model="edit.unit"
                placeholder="请选择单位"
              >
                <el-option
                  v-for="item in unitList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="工艺流程">
              <el-select
                filterable
                size="mini"
                clearable
                v-model="edit.processFlowId"
                @change="selectTecProName"
                placeholder="请选择工艺流程"
              >
                <el-option
                  v-for="(item, index) in workmanship"
                  :key="index"
                  :label="item.tecProName"
                  :value="item.pkProTecPro"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="从产品复制工序" label-width="130px">
              <el-select
                v-model="product"
                clearable
                size="mini"
                filterable
                @change="copyProduct"
                placeholder="从产品复制工序"
              >
                <el-option
                  v-for="(item, index) in productNameList"
                  :key="index"
                  :label="item.productName"
                  :value="item.pkProProduct"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="添加单个工序">
              <el-select
                clearable
                size="mini"
                filterable
                v-model="pkCraftInfo"
                @change="addOneCraftInfo"
                placeholder="添加单个工序"
              >
                <el-option
                  v-for="(item, index) in craftInfList"
                  :key="index"
                  :label="item.craftName"
                  :value="item.pkCraftInfo"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-row>
        <el-row type="flex" style="width: 100%; height: 63%">
          <div style="width: 100%; height: 100%">
            <el-table
              :data="productCraftList"
              border
              row-key="pkCraftInfo"
              ref="dragTable"
              height="90%"
              :span-method="mergeTable"
              style="width: 100%"
            >
              <el-table-column
                width="50"
                align="center"
                type="index"
                label="序号"
              >
              </el-table-column>
              <el-table-column
                prop="craftName"
                label="工序名称"
                align="center"
                width="180"
              >
                <template slot-scope="scope">
                  <el-input disabled v-model="scope.row.craftName"></el-input>
                </template>
              </el-table-column>
              <el-table-column
                prop="craftPriceNum"
                label="计件单价（元）"
                align="center"
                width="160"
              >
                <template slot-scope="scope">
                  <el-input-number
                    v-model="scope.row.craftPriceNum"
                    :min="0"
                    size="mini"
                    :max="1000"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column
                prop="craftPriceTime"
                label="计时单价（元/小时）"
                align="center"
                width="160"
              >
                <template slot-scope="scope">
                  <el-input-number
                    v-model="scope.row.craftPriceTime"
                    :min="0"
                    size="mini"
                    :max="1000"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column prop="craftRemark" label="备注" align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.craftRemark"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="调整顺序" width="100" align="center">
                <template>
                  <el-button class="move" type="text" size="small"
                    >拖 拽</el-button
                  >
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100" align="center">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    @click="removeCraft(scope.$index, scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
              <el-table-column
                prop="file"
                label="照片"
                width="150"
                align="center"
                :aria-rowspan="productCraftList.length"
              >
                <template slot-scope="scope">
                  <div class="choose-img" v-if="imageUrl">
                    <el-image
                      style="width: 100px; height: 100px"
                      :src="imageUrl"
                    ></el-image>
                    <el-button size="mini" @click="imageUrl = ''" type="text"
                      >删除照片</el-button
                    >
                  </div>
                  <div v-else>
                    <el-upload
                      :headers="imgUpload.headers"
                      :action="imgUpload.url"
                      :limit="limit"
                      :show-file-list="false"
                      :on-exceed="handleExceed"
                      :on-success="handlePictureSuccess"
                      :on-preview="handlePictureCardPreview"
                      :before-upload="beforeAvatarUpload"
                    >
                      <el-button size="small">
                        选择照片
                        <i class="el-icon-upload el-icon--right"></i>
                      </el-button>
                    </el-upload>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-row>
        <el-row style="text-align: center"
          ><el-button
            type="primary"
            v-hasPermi="['business:product:add']"
            @click="onSubmit"
            >保存</el-button
          ></el-row
        >
      </div>
    </el-card>
  </div>
</template>
<script>
import {
  getAllProductListApi,
  addProductApi,
  getTecProAllListApi,
  getUnitListAllApi,
} from "@/api/product/product.js";
import { getAllCraftInfoListApi } from "@/api/craftInfo/craftInfo.js";
import Sortable from "sortablejs";
//--------导入token
import { getToken } from "@/utils/auth";
export default {
  components: {},
  watch: {},
  computed: {},
  data() {
    return {
      searchData: {
        pageNum: 1,
        pageSize: 10,
        productName: "",
      },
      edit: {
        productName: "",
        unit: "",
      },
      workmanship: [],
      productCraftList: [],
      productNameList: [],
      craftInfList: [],
      unitList: [], //单位
      pkCraftInfo: undefined,
      product: "",
      type: "",
      imageUrl: "",
      limit: 1,
      imgUpload: {
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        // 图片上传的方法地址:
        url: process.env.VUE_APP_BASE_API + "/common/upload",
      },
    };
  },
  created() {
    this.type = this.$route.query.type;
    if (this.type == "edit") {
      const productInfo = JSON.parse(this.$route.query.productInfo);
      this.edit.productName = productInfo.productName;
      this.edit.unit = productInfo.unit;
      this.edit.pkProProduct = productInfo.pkProProduct;
      this.productCraftList = productInfo.productCraftList;
      this.imageUrl = productInfo.file;
    }
  },
  mounted() {
    // 查询所有工艺列表
    this.getTecProAllList();
    this.getAllProductList();
    this.getAllCraftInfoList();
    this.getUnitListList();
    if (this.type == "edit") {
      this.initSortable();
    }
  },
  methods: {
    // 查询所有产品
    async getAllProductList() {
      const { data: res } = await getAllProductListApi();
      this.productNameList = res;
    },

    // 查询所有工艺
    async getTecProAllList() {
      const { data: res } = await getTecProAllListApi();
      this.workmanship = res;
    },

    // 查询工序所有列表
    async getAllCraftInfoList() {
      const res = await getAllCraftInfoListApi(this.searchData);
      this.craftInfList = res.data;
    },

    // 获取单位列表
    async getUnitListList() {
      const res = await getUnitListAllApi();
      this.unitList = res.data;
    },

    // 选中工艺流程
    selectTecProName(e) {
      if (!e) {
        return;
      }
      const productCraftList = this.workmanship.filter(
        (item) => item.pkProTecPro == e
      );
      this.productCraftList = productCraftList[0].proCraftTecVoList;
      this.initSortable();
    },
    // 从产品复制
    copyProduct(e) {
      if (!e) {
        return;
      }
      const productCraftList = this.productNameList.filter(
        (item) => item.pkProProduct == e
      );
      this.edit.unit = productCraftList[0].unit;
      this.productCraftList = productCraftList[0].productCraftList;
      this.initSortable();
    },
    // 添加单个工序
    addOneCraftInfo(e) {
      if (!e) {
        return;
      }
      // 判断是否存在相同的工序
      const existingIndex = this.productCraftList.findIndex(
        (item) => item.pkCraftInfo === e
      );
      if (existingIndex !== -1) {
        // 如果存在相同的工序，则删除原有的工序
        this.productCraftList.splice(existingIndex, 1);
      }
      const productCraftList = this.craftInfList.filter(
        (item) => item.pkCraftInfo == e
      );
      // 向列表中添加新的工序
      this.productCraftList.push({
        pkCraftInfo: e,
        craftName: productCraftList[0].craftName,
        craftOrder: this.productCraftList.length + 1,
        craftPriceNum: "",
        craftPriceTime: "",
        craftRemark: productCraftList[0].craftRemark,
      });
      this.initSortable();
    },

    // 删除工序
    removeCraft(index, row) {
      this.productCraftList.splice(index, 1);
      this.initSortable();
    },

    // 合并照片列单元格
    mergeTable({ row, column, rowIndex, columnIndex }) {
      // console.log(columnIndex);
      if (columnIndex === 7) {
        return {
          rowspan: this.productCraftList.length,
          colspan: 1,
        };
      }
    },
    // 覆盖默认的上传行为
    requestUpload() {},
    //图片上传前的相关判断
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type == "image/png";
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 5MB!");
      }
      return isJPG && isLt2M;
    },
    //图片预览
    handlePictureCardPreview(file) {
      this.imageUrl = file.url;
    },
    //图片上传成功后的回调
    handlePictureSuccess(res, file) {
      //设置图片访问路径 （url 后台传过来的的上传地址）
      this.imageUrl = file.response.url;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传链接LOGO图片数量不能超过 ${this.limit} 个!`);
    },
    // 初始化sort
    initSortable() {
      let _this = this;
      // 获取表格row的父节点
      const ele = this.$refs.dragTable.$el.querySelector(
        ".el-table__body > tbody"
      );
      Sortable.create(ele, {
        animation: 150, //动画
        handle: ".move", //指定拖拽目标，点击此目标才可拖拽元素(此例中设置操作按钮拖拽)
        // 结束拖动事件
        onEnd: ({ newIndex, oldIndex }) => {
          // console.log(
          //   "结束拖动",
          //   `拖动前索引${oldIndex}---拖动后索引${newIndex}`
          // );
          // 将拖动后的新顺序重新组合
          const currRow = _this.productCraftList.splice(oldIndex, 1)[0];
          this.productCraftList.splice(newIndex, 0, currRow);
        },
      });
    },

    onSubmit() {
      this.$refs["edit"].validate((valid) => {
        if (!valid) return;
        if (this.productCraftList.length < 1) {
          this.$message.error("工序不能为空");
          return;
        }
        let params = {
          file: this.imageUrl,
          pkProProduct: this.edit.pkProProduct || "",
          productName: this.edit.productName,
          unit: this.edit.unit,
          productCraftList: this.productCraftList.map((item, index) => ({
            craftName: item.craftName,
            craftOrder: index + 1,
            craftPriceNum: item.craftPriceNum,
            craftPriceTime: item.craftPriceTime,
            craftRemark: item.craftRemark,
            pkCraftInfo: item.pkCraftInfo,
          })),
          proCraftUsers: [
            {
              craftName: "",
              pkCraftInfo: "",
              pkProCraftUser: "",
              userId: "",
              userName: "",
            },
          ],
        };
        this.addProduct(params);
      });
    },

    // 新增产品
    async addProduct(params) {
      const res = await addProductApi(params);
      console.log(res);
      this.$message.success("新增成功");
      this.$nextTick(() => {
        this.back();
      });
    },
    // 返回列表页
    back() {
      // this.closePage(this.$route);
      this.$router.push("/productCenter/productSet");
    },
  },
};
</script>

<style lang="scss">
.container {
  padding-top: 20px;
}
.box-card {
  width: 100%;
  height: 100%;
}
.el-card__body {
  height: 100%;
}
.photo {
  display: flex;
  flex-direction: column;
  width: 10%;
  height: 90%;
  border: 1px solid #dfe6ec;
  border-left: none;
}
.photo-title {
  border-bottom: 1px solid #dfe6ec;
  text-align: center;
  word-break: break-word;
  background-color: #f8f8f9;
  color: #515a6e;
  height: 44px;
  line-height: 44px;
  font-size: 13px;
  font-weight: 600;
}
.photo-style {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.choose-img {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
</style>
